<template>
  <div class="app">
    <div class="search-bar">
      <el-form :model="naturalSearchData" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="招商局员工号" style="margin-bottom: 5px;">
              <el-input v-model="naturalSearchData.cmhkPersonId" size="medium" class="select"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" style="margin-bottom: 5px;">
              <el-input v-model="naturalSearchData.nameChi" size="medium" class="select" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div style="margin-top: 3px;">
              <el-button icon="el-icon-search" type="primary" size="small" @click="naturalHandleSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" size="small" @click="naturalHandleClear">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-show="canUsed" class="button-bar">
      <el-button icon="el-icon-plus" type="primary" size="small" @click="naturalHandleAdd">新增</el-button>
      <el-button icon="el-icon-delete" type="danger" size="small" @click="naturalHandleDel">删除</el-button>
    </div>
    <div ref="ref2" :class="canUsed?'table-box':'table-box2'">
      <tableComponent
        class="table"
        :height="naturalHeight"
        :data="naturalTableData || []"
        :columns="naturalTableColumns"
        @change="naturalTablePage"
        :table-option="naturalTableOption"
        :page-option="naturalPageOption"
        :total="naturalTotal"
        @selectionChange="naturalHandleSelectChange"
      >
        <template slot-scope="scope">
          <div class="options">
            <el-button type="text" @click="naturalSeeItem(scope.scope.row)">查看</el-button>
            <el-button v-show="canUsed" type="text" @click="naturalEditItem(scope.scope.row)">修改</el-button>
          </div>
        </template>
      </tableComponent>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" label-position="left" style="padding: 0 40px;" :disabled="disabled">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="姓名" prop="nameChi" style="margin-left: -9px">
              <el-input class="input" v-model="form.nameChi" size="small" style="width: calc(100% - 9px); margin-left: 9px"></el-input>
            </el-form-item>
            <el-form-item label="是否招商局员工" prop="ifcmhk" style="margin-left: -9px">
              <el-select v-model="form.ifcmhk" :class="[ifBtn?'select-btn':'select']" size="small" @change="cmhkChange" style="width: calc(100% - 9px); margin-left: 9px">
                <el-option
                  v-for="item in ifcmhkOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-button v-if="ifBtn" type="text" size="mini" @click="selectNum">查询工号</el-button>
            </el-form-item>
            <el-form-item label="招商局员工号" prop="cmhkPersonId" v-show="ifCmhkPeople">
              <el-input v-model="form.cmhkPersonId" class="select" size="small"></el-input>
            </el-form-item>
            <el-form-item label="所属地区" prop="location">
              <el-cascader
                v-model="form.location"
                :options="options"
                @change="handleChange"
                :props="prop"
                size="small"
                class="select"
                filterable
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input class="input" v-model="form.email" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="nameEng">
              <el-input class="input" v-model="form.nameEng" size="small"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择" class="select" size="small">
                <el-option label="男" value="M"></el-option>
                <el-option label="女" value="F"></el-option>
                <el-option label="未知" value="U"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="mobilePhone">
              <el-input class="input" v-model="form.mobilePhone" size="small"></el-input>
            </el-form-item>
            <el-form-item label="固定电话" prop="telephone">
              <el-input class="input" v-model="form.telephone" size="small"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancle">取 消</el-button>
        <el-button v-show="!disabled" type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择员工" :visible.sync="dialogVisibleSelect" width="60%">
      <div ref="people" class="people-box">
        <tableComponent
          class="table"
          :data="tableData || []"
          :columns="tableColumns"
          :table-option="tableOption"
          @selectionChange="selectCheckd"
          :height="peopleHeight"
        >
        </tableComponent>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSelect = false">取 消</el-button>
        <el-button type="primary" @click="handleSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableComponent from '@/components/Table/table'
import { naturalTableColumns, tableColumns } from "./index.js"
import { getNaturalData, addNaturalData, editNaturalData, seeNaturalData, delNaturalData, queryUserByEmpName } from '@/api/modules/legalAndNatural.js'
import { allArea } from '@/api/modules/propertyRight.js'
export default {
  components: {
    tableComponent
  },
  data() {
    return {
      naturalSearchData: {
        nameChi: '',
        cmhkPersonId: '',
        page: {
          pageNum: 1,
          pageSize: 10
        }
      },
      searchOption: [
        { label: '国内', value: '1' },
        { label: '国外', value: '2' }
      ],
      naturalHeight: null,
      naturalTableColumns,
      naturalTableData: [],
      naturalTableOption: {
        isShowOperate: true,
        isMultiSelect: true,
        operateWidth: '100px'
      },
      naturalPageOption: {
        pageNum: 1,
        pageSize: 10
      },
      naturalTotal: 0,
      naturalIds: [], // 存储自然人表格数据ID用于删除或批量删除
      // dialogParams============================================
      dialogVisible: false,
      title: '',
      form: {
        nameChi: '',
        nameEng: '',
        sex: '',
        addressProvince: '',
        cmhkPersonId: '',
        mobilePhone: '',
        telephone: '',
        email: '',
        ifcmhk: '2',
        location: []
      },
      disabled: false,
      rules: {
        nameChi: [{required: true, message: '请输入法人名称', trigger: 'blur'}],
        ifcmhk: [{required: true, message: '请选择是否招商局员工', trigger: 'change'}]
      },
      ifcmhkOption: [
        { label: '是', value: '1' },
        { label: '否', value: '2' }
      ],
      ifCmhkPeople: false,
      options: [],
      prop: {
        label: 'name',
        value: 'code',
        children: 'child'
      },
      ifBtn: false,
      // 选择人======================
      tableData: [],
      tableColumns,
      peopleHeight: null,
      tableOption: {
        isMultiSelect: true
      },
      dialogVisibleSelect: false,
      savePeopleMsg: {},
      canUsed: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.naturalHeight = this.$refs.ref2.offsetHeight
    })
    window.onresize = () => {
      this.naturalHeight = this.$refs.ref2.offsetHeight
    }
    allArea().then(res => {
      if (res.data.code === '0') {
        this.options = this.getTreeData(res.data.body)
      }
    })
    const query = this.$route.query.name
    if (query != '') {
      this.naturalSearchData.nameChi = query
      this.initData(this.naturalSearchData)
    } else {
      const key = this.$store.state.key.resourceCode
      if (key === '0') {
        this.canUsed = false
      } else {
        this.canUsed = true
      }
      this.initData(this.naturalSearchData)
    }
  },
  destroyed(){
    window.onresize = null
  },
  methods: {
    selectNum() {
      if (this.form.nameChi === '') {
        this.$message.error('请输入姓名')
      } else {
        this.dialogVisibleSelect = true
        this.$nextTick(() => {
          this.peopleHeight = this.$refs.people.offsetHeight
        })
        window.onresize = () => {
          this.peopleHeight = this.$refs.people.offsetHeight
        }
        const data = {
          empName: this.form.nameChi
        }
        queryUserByEmpName(data).then(res => {
          if (res.data.code === '200') {
            this.tableData = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    selectCheckd(val) {
      if (val.length > 1) {
        this.$message.error('只能选择一条数据')
      } else  {
        this.savePeopleMsg = val[0]
      }
    },
    handleSelect() {
      this.dialogVisibleSelect = false
      this.form.cmhkPersonId = this.savePeopleMsg.psId
      this.form.nameChi = this.savePeopleMsg.empName
      this.form.email = this.savePeopleMsg.email
      this.form.sex = this.savePeopleMsg.sex
    },
    cmhkChange(val) {
      if (val === '1') {
        this.ifCmhkPeople = true
        this.ifBtn = true
      } else {
        this.form.email = ''
        this.form.sex = ''
        this.form.cmhkPersonId = ''
        this.ifCmhkPeople = false
        this.ifBtn = false
      }
    },
    initData(params) {
      getNaturalData(params).then(res => {
        if (res.data.code === '0') {
          this.naturalTableData = res.data.body.list
          this.naturalTotal = res.data.body.total
        }
      })
    },
    // 自然人查询
    naturalHandleSearch() {
      this.initData()
    },
    // 分页
    naturalTablePage(val) {
      this.naturalSearchData.page = val
      this.initData()
    },
    // 自然人重置
    naturalHandleClear() {
      this.naturalSearchData.nameChi = ''
      this.naturalSearchData.cmhkPersonId = ''
    },
    // 自然人新增
    naturalHandleAdd() {
      this.dialogVisible = true
      this.ifBtn = false
      this.title = '新增自然人信息'
      this.disabled = false
      this.ifCmhkPeople = false
      this.form.ifcmhk = '2'
      this.form.cmhkPersonId = ''
    },
    // 自然人查看
    naturalSeeItem(row) {
      this.dialogVisible = true
      this.title = '查看自然人信息'
      this.disabled = true
      const params = {
        id: row.id
      }
      seeNaturalData(params).then(res => {
        if (row.cmhkPersonId === null) {
          this.ifCmhkPeople = false
          this.form = res.data.body
          this.form.ifcmhk = '2'
        } else  {
          this.ifCmhkPeople = true
          this.form = res.data.body
          this.form.ifcmhk = '1'
        }
      })
    },
    // 自然人修改
    naturalEditItem(row) {
      console.log(row);
      this.dialogVisible = true
      this.title = '修改自然人信息'
      this.disabled = false
      const params = {
        id: row.id
      }
      seeNaturalData(params).then(res => {
        if (row.cmhkPersonId === null) {
          this.ifCmhkPeople = false
          this.form = res.data.body
          this.form.ifcmhk = '2'
        } else if (row.cmhkPersonId === '') {
          this.ifCmhkPeople = false
          this.form = res.data.body
          this.form.ifcmhk = '2'
        } else  {
          this.ifCmhkPeople = true
          this.ifBtn = true
          this.form = res.data.body
          this.form.ifcmhk = '1'
        }
      })
    },
    // 自然人表格复选框被选中
    naturalHandleSelectChange(row) {
      console.log(row)
      const data = row
      this.naturalIds = []
      data.forEach(item => {
        this.naturalIds.push(item.id)
      })
      
    },
    // 自然人删除
    naturalHandleDel() {
      if (!this.naturalIds.length) {
        this.$message({
          type: 'error',
          message: '请选择要删除的数据'
        })
      } else {
        this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delNaturalData(this.naturalIds).then(res => {
            if (res.data.code === '0') {
              this.$message.success('删除成功')
              this.initData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // dialogFunction======================================
    handleSubmit() {
      if (this.title === '新增自然人信息') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            addNaturalData(this.form).then(res => {
              if (res.data.code === '0') {
                this.$message.success('新增成功')
                this.resetForm('form')
                this.dialogVisible = false
                this.initData()
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else {
            return false
          }
        })
      } else if (this.title === '修改自然人信息') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            editNaturalData(this.form).then(res => {
              if (res.data.code === '0') {
                this.$message.success('修改成功')
                this.resetForm('form')
                this.dialogVisible = false
                this.initData()
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else {
            return false
          }
        })
      }
    },
    getTreeData(data){
      // 循环遍历json数据
      for(let i=0;i<data.length;i++){
        if(data[i].child.length<1){
          // children若为空数组，则将children设为undefined
          data[i].child = undefined
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].child)
        }
      }
      return data
    },
    // 选择所在地区
    handleChange(val) {
      this.form.location = val
    },
    handleCancle() {
      this.resetForm('form')
      this.dialogVisible = false
    },
    // 弹窗关闭前的回调
    handleClose() {
      this.resetForm('form')
      this.dialogVisible = false
    },
    // 清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  }
}
</script>

<style lang="less" scoped>
  .app {
    height: 100%;
    .search-bar {
      width: 100%;
      background-color: #ffffff;
      margin-bottom: 10px;
      padding: 10px 0px;
    }
    .button-bar {
      width: calc(100% - 40px);
      padding: 10px 20px;
      background-color: #ffffff;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 260px);
      .table {
        height: 100%;
      }
    }
    .table-box2 {
      width: 100%;
      height: calc(100vh - 210px);
      .table {
        height: 100%;
      }
    }
    .people-box {
      height: 50vh;
    }
    .select {
      width: 100%;
    }
    .select-btn {
      width: calc(100% - 69px) !important;
    }
    .dialog-footer {
      padding: 0 20px 20px;
    }
  }
</style>
<style>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-input.is-disabled .el-input__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
  .el-textarea.is-disabled .el-textarea__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
</style>